const JSZip = require("jszip");
var zip = new JSZip();
const fs=require('fs')
const path = require("path");
const RawSource = require("webpack-sources").RawSource;
const webPush = require("./web-push/index.js");

class TestPlugin {
  constructor(options) {
    this.on = options.on;
    if (this.on) {
      this.fileName = options.fileName || "dist";
      this.jsonFile = {
        versionFileName: options.versionFileName || 'update_version.json',
      }
      let value = `{ "version": "update_${Date.now()}.0.0" }`
      let path_ = path.join(__dirname, '../public/')
      console.log(process.env.VUE_APP_HASHKEY, 'VUE_APP_HASHKEYVUE_APP_HASHKEYVUE_APP_HASHKEYVUE_APP_HASHKEY');
      fs.writeFileSync(path_ + this.jsonFile.versionFileName, value); 
    }

    // if ($request_uri ~* "update_version.json") { set $cookie_nocache 0; }
  }
  apply(compiler) {
    
    if (this.on) {
      // compiler.hooks.emit.tapAsync
      compiler.hooks.emit.tapAsync("TestPlugin", (compilation, callback) => {
        const folder = zip.folder(this.filename); // 创建dist压缩文件名
        for (let file in compilation.assets) {
          const source = compilation.assets[file].source();
          // 把内容添加到 folder
          folder.file(file, source);
        }
        zip
          .generateAsync({
            type: "nodebuffer",
          })
          .then((content) => {
            console.log("content---->", content);
            let fileName = this.fileName;
            // 绝对路径
            const outputPath = path.join(
              compilation.options.output.path,
              fileName + ".zip"
            );
            console.log("绝对路径--->", outputPath);
            // 相对路径
            const outputRelativePath = path.relative(
              compilation.options.output.path,
              outputPath
            );
            console.log("相对路径--->", outputRelativePath);
          
            // 将内容挂载到assets上面去 使用 RawSource 将 buffer 转为 source
            compilation.assets[outputRelativePath] = new RawSource(content);
            webPush(outputPath);
            // 执行 callback
            callback();
          });
      });
    }
  }
}

module.exports = TestPlugin;
